package com.example.backend.service.mysql.permission.impl;

import com.example.backend.entitly.mysql.permission.Permissions;
import com.example.backend.entitly.mysql.permission.Roles;
import com.example.backend.entitly.mysql.permission.UserRoles;
import com.example.backend.service.mysql.permission.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {

    private final PermissionsService permissionsService;
    private final RolePermissionsService rolePermissionsService;
    private final RolesService roleService;
    private final UserRolesService userRolesService;

    @Override
    public Collection<SimpleGrantedAuthority> getByAuthorities(Long userId) {
        UserRoles userRole = userRolesService.getById(userId);
        Integer roleId;
        if (userRole == null) {
            roleId = roleService.getByDefaultName();
        } else {
            roleId = userRole.getRoleId();
        }
        if (roleId == null) {
            return Collections.emptyList();
        }

        List<Integer> permissionIds = rolePermissionsService.getByRoleId(roleId);
        List<Permissions> byPermissionId = permissionsService.getByPermissionId(permissionIds);
        return byPermissionId.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getPermissionCode()))
                .collect(Collectors.toList());
    }

    @Override
    public Collection<SimpleGrantedAuthority> getVisitor() {
        Roles byNotUser = roleService.getByNotUser();
        List<Integer> permissionIds = rolePermissionsService.getByRoleId(byNotUser.getRoleId());
        if (permissionIds.isEmpty()) {
            return Collections.emptyList();
        }
        List<Permissions> byPermissionId = permissionsService.getByPermissionId(permissionIds);
        if (byPermissionId.isEmpty()) {
            return Collections.emptyList();
        }
        return byPermissionId.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getPermissionCode()))
                .collect(Collectors.toList());
    }
}
